package com.wangyu.talents.common.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JWT工具类
 *
 * @author wangyu
 * @Date 2018-09-10 13:21
 */
public class JWTUtil {

  private static Logger logger = LoggerFactory.getLogger(JWTUtil.class);

  /**
   * 设置token过期时间为5分钟
   */
  private static final long EXPIRE_TIME = 5 * 60 * 1000;

  /**
   * 设置secret签名密钥
   */
  private static final String SECRET = "wangyu";

  /**
   * 生成签名,5min后过期
   *
   * @param username 用户名
   * @return 加密的token
   */
  public static String createToken(String username) {
    try {
      Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
      Algorithm algorithm = Algorithm.HMAC256(SECRET);
      // 附带username信息
      return JWT.create()
          .withClaim("username", username)
          .withExpiresAt(date)
          .sign(algorithm);
    } catch (UnsupportedEncodingException e) {
      return null;
    }
  }

  /**
   * 校验token是否正确
   *
   * @param token token值
   * @param userName 用户名
   */
  public static boolean verify(String token, String userName) {
    try {
      Algorithm algorithm = Algorithm.HMAC256(SECRET);
      JWTVerifier verifier = JWT.require(algorithm)
          .withClaim("username", userName)
          .build();
      verifier.verify(token);
      return true;
    } catch (UnsupportedEncodingException e) {
      return false;
    }
  }

  /**
   * 获取token中的信息
   */
  public static String getUserName(String token) {
    try {
      DecodedJWT jwt = JWT.decode(token);
      logger.info(jwt.getClaims().toString());
      return jwt.getClaim("username").asString();
    } catch (JWTDecodeException e) {
      return null;
    }
  }
}
